<?php

//判断是否序列化值
function is_serialized( $data ) {
	$data = trim( $data );      
	if ( preg_match( '/^a:[0-9]+:.*;$/s', $data )){       
		return 1;      
	}else{
		return 0;
	}
	
}

//显示404页面
function show404 ( $message ) {
	$template = load_libra('smarty');
	$template->assign('message',$message);
	$template->template_dir = ROOT . "ui/templates";
	$template->display('public/404.htm');
	exit;
}

//显示错误页面
function showEror ( $message,$url ) {
	$template = load_libra('smarty');
	$template->assign('message',$message);
	$template->assign('url',$url);
	$template->template_dir = ROOT . "ui/templates";
	$template->display('public/Error.htm');
	exit;
}

//显示404页面
function showSuc ( $message,$url="" ) {
	$template = load_libra('smarty');
	$template->assign('message',$message);
	$template->assign('url',$url);
	$template->template_dir = ROOT . "ui/templates";
	$template->display('public/Suc.htm');
	exit;
}

//获取请求的url

function getlasturl(){
	return ($_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
}

//读取CSV文件为数组
function getCSVdata($filename){
	$row = 1;//第一行开始
	if(($handle = fopen($filename, "r")) !== false)
	{
		while(($dataSrc = fgetcsv($handle)) !== false)
		{
			$num = count($dataSrc);
			for ($c=0; $c < $num; $c++)//列 column
			{
				if($row === 1)//第一行作为字段
				{
					$dataName[] = iconv( "GBK//IGNORE","UTF-8", $dataSrc[$c]);//字段名称
				}
				else
				{
					foreach ($dataName as $k=>$v)
					{
						if($k == $c)//对应的字段
						{
							$data[$v] = iconv( "GBK//IGNORE","UTF-8",$dataSrc[$c]);
						}
					}
				}
			}
			if(!empty($data))
			{
				$dataRtn[] = $data;
				unset($data);
			}
			$row++;
		}
		fclose($handle);
		return $dataRtn;
	}
}

// 输出方法
function dump($arr) {
	echo "<pre>";
	var_dump ( $arr );
	echo "<pre>";
}

// 输出断点
function dumpe($arr) {
	echo "<pre>";
	var_dump ( $arr );
	echo "<pre>";
	exit;
}

function DeleteHtml($str){

	$str = trim($str);

	$str = strip_tags($str,"");

	$str = ereg_replace("\t","",$str);

	$str = ereg_replace("\r\n","",$str);

	$str = ereg_replace("\r","",$str);

	$str = ereg_replace("\n","",$str);

	$str = ereg_replace(" "," ",$str);

	return trim($str);

}

function get_class_all_methods($class,$isdum=0){
	$r = new ReflectionClass($class);
	foreach($r->getMethods() as $key=>$methodObj){
		
		if($methodObj->class!=$class){
			$methods[$key]['isbaseclass']=1;
		}
		
		$methods['baseclass'][$key] = $methodObj->class;
		$methods[$key]['class'] = $methodObj->class;
			
		if($methodObj->isPrivate())
			$methods[$key]['type'] = 'private';
		elseif($methodObj->isProtected())
		$methods[$key]['type'] = 'protected';
		else
			$methods[$key]['type'] = 'public';
		$methods[$key]['name'] = $methodObj->name;
		
		
		
		
		
	}
	if($isdum==1){
		dump($methods);
	}else{
		return $methods;
	}
}

function prepareJSON($input){
	$imput = mb_convert_encoding($input,'UTF-8','ASCII,UTF-8,ISO-8859-1');
	if(substr($input,0,3) == pack("CCC",0xEF,0xBB,0xBF)) $input = substr($input,3);
	return $input;
}

//请求外部链接

function requestserver($url,$param,$method='get') {
	
	if(function_exists('curl_init')){
		// user_agent
		$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
		// 伪造header
		$header = array ('Accept-Language: zh-cn', 'Connection: Keep-Alive', 'Cache-Control: no-cache' );
		$ch = curl_init ();
		$timeout = 5;
		
		#伪装浏览器 
		curl_setopt ( $ch, CURLOPT_REFERER, $url );
		#设置模拟浏览器
		curl_setopt ( $ch, CURLOPT_USERAGENT, $useragent );
		#设置请求header
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
	
		
		
		if($method=='post'){
			#设置请求的post项
			curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		}else{
			foreach($param as $key=>$value){
				$url.="&".$key."=".$value;
			}
		}
		
		#设置请求url
		curl_setopt ( $ch, CURLOPT_URL, $url );
		
		#设置将结果返回到变量中
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		
		curl_setopt ( $ch, CURLOPT_VERBOSE, 0 );
		#设置过期时间
		curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
		$file_contents = curl_exec ( $ch );
		
		$file_contents = prepareJSON($file_contents);
		
		#关闭进程 
		curl_close ( $ch );
	}else{
		
	}
	
	return $file_contents;
}


function get_url_content($url,$param,$method='get') {

	if(function_exists('curl_init')){
		// user_agent
		$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
		// 伪造header
		$header = array ('Accept-Language: zh-cn', 'Connection: Keep-Alive', 'Cache-Control: no-cache' );
		$ch = curl_init ();
		$timeout = 5;

		#伪装浏览器
		curl_setopt ( $ch, CURLOPT_REFERER, $url );
		#设置模拟浏览器
		curl_setopt ( $ch, CURLOPT_USERAGENT, $useragent );
		#设置请求header
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );

		#设置请求url
		curl_setopt ( $ch, CURLOPT_URL, $url );

		if($method=='get'){
			#设置请求的get项
			curl_setopt($ch, CURLOPT_GETFIELDS, $param);
		}elseif($method=='post'){
		#设置请求的post项
			curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		}else{
			
		}


			#设置将结果返回到变量中
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

			curl_setopt ( $ch, CURLOPT_VERBOSE, 0 );
			#设置过期时间
			curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
			$file_contents = curl_exec ( $ch );
			#关闭进程
			curl_close ( $ch );
	}else{

}

return $file_contents;
}

//加载组件
function load_libra($lname) {
	$libra_class = array ('excel', 'pinyin', 'smarty', 'zip','uploadimg','csv','validate','snoopy');
	if (in_array ( $lname, $libra_class )) {
		return include_once LIB_ROOT . 'api_' . $lname . '.php';
	} else {
		echo '错误的附件名称！';
	}
}

//加载model
function load_model($lname,$path=1) {
	global $_SGLOBAL;
	$pathstr='';
	
	if($path===0){
		
	}elseif($path!=1 ){
		$pathstr=$path."/";
	}elseif(isset($_SGLOBAL['path'])){
		$pathstr=$_SGLOBAL['path']."/";
	}
	
	$modelname = 'model_' . $lname;
	
	$classname = 'Model'.$lname;
	
	
	require_once MODEL_ROOT . $pathstr.$modelname . '.php';
	$model = new $classname ();
	return $model;
}

/**
 * 生成服务URL方法
 * @param string $urlstr 以/号按顺序生成URL相应 的字段 ，path action method
 * @param array $andarr 二维数组,key为名字，value为对应的值
 * @return string url
 */
function urlforservice($urlstr,$andarr=array(),$path=1) {
	
	global $_SGLOBAL;
	
	
	/* if($path=1 && ($_SGLOBAL['path'])){
		$urlstr=$_SGLOBAL['path']."/".$urlstr;
	} */
	
	
	if($path===0){
		
	}elseif($path!=1 ){
		$urlstr=$path."/".$urlstr;
	}elseif(isset($_SGLOBAL['path'])){
		$urlstr=$_SGLOBAL['path']."/".$urlstr;
	}
	
	$url_array = explode ( '/', $urlstr );
	
	if(count($url_array)==3){		
		
		$url = "/?path=".$url_array[0]."&action=" . $url_array [1] . '&method=' . $url_array [2];
	}else{
		if(!isset($url_array[1])){
			$url_array[0] = $urlstr;
			$url_array[1] = 'index';
		}
		
		$url="/?action=".$url_array [0];
		$url.=empty($url_array [1])?'':('&method=' .$url_array [1]);
		
	}
	
	
	
	
	if(isset($andarr)){
		foreach($andarr as $k => $v)
		{
			$url .="&$k=".urlencode($v); 
		}
	}
	
	/* if($andarr==1){
		echo $urlstr;echo "<br>";
		dump($url_array);
		echo $url;
		dumpe("HelloWorld");
	} */
	
	return $_SERVER['SERVER_NAME'].$url;
}

/**
 * 生成URL方法
 * @param string $urlstr 以/号按顺序生成URL相应 的字段 ，path action method
 * @param array $andarr 二维数组,key为名字，value为对应的值
 * @return string url
 */
function url($urlstr,$andarr=array(),$path=1) {
	
	global $_SGLOBAL;
	
	
	/* if($path=1 && ($_SGLOBAL['path'])){
		$urlstr=$_SGLOBAL['path']."/".$urlstr;
	} */
	
	
	if($path===0){
		
	}elseif($path!=1 ){
		$urlstr=$path."/".$urlstr;
	}elseif(isset($_SGLOBAL['path'])){
		$urlstr=$_SGLOBAL['path']."/".$urlstr;
	}
	
	$url_array = explode ( '/', $urlstr );
	
	if(count($url_array)==3){		
		
		$url = "/?path=".$url_array[0]."&action=" . $url_array [1] . '&method=' . $url_array [2];
	}else{
		if(!isset($url_array[1])){
			$url_array[0] = $urlstr;
			$url_array[1] = 'index';
		}
		
		$url="/?action=".$url_array [0];
		$url.=empty($url_array [1])?'':('&method=' .$url_array [1]);
		
	}
	
	
	
	
	if(isset($andarr)){
		foreach($andarr as $k => $v)
		{
			$url .="&$k=".urlencode($v); 
		}
	}
	
	/* if($andarr==1){
		echo $urlstr;echo "<br>";
		dump($url_array);
		echo $url;
		dumpe("HelloWorld");
	} */
	
	return $url;
}

//格式化输出时间戳
function format_time($time){
	return date("Y-m-d H:i:s",$time); 
}

//分页方法
function fenye($fenyeurl, $page, $totalnum, $perpage, $rewrite = 0) {
	$page = max ( $page, 1 );
	$totalpage = ceil ( $totalnum / $perpage );
	$rangepage = 6;
	
	$startpage = max ( 1, $page - $rangepage );
	$endpage = min ( $totalpage, $startpage + $rangepage * 2 - 1 );
	$startpage = min ( $startpage, $endpage - $rangepage * 2 + 1 );
	if ($startpage < 1)
		$startpage = 1;
	
	$fileext = $rewrite ? '.html' : '';
	$html = '';
	$html .= '<td width="49"><div align="center"><a href="' . $fenyeurl . '1">首页</a></div></td>';
	$html .= $page > 1 ? '<td width="49"><div align="center"><a href="' . $fenyeurl . ($page - 1) . '">上一页</a></div></td>' : '';
	for($i = $startpage; $i <= $endpage; $i ++) {
		$html .= '<td width="49" style=' . ($page == $i ? ' background-color:red;' : '') . '><div align="center"><a href="' . $fenyeurl . $i . $fileext . '">' . $i . '</a></div></td>';
		if ($i == $totalpage)
			break;
	}
	$html .= $page < $totalpage ? '<td width="49"><div align="center"><a href="' . $fenyeurl . ($page + 1) . '">下一页</a></div></td>' : '';
	$html .= '<td width="49"><div align="center"><a href="' . $fenyeurl . $totalpage . '">末页</a></div></td>';
	
	return $html;
}

//生成图片路径方法

function iconPathBuild($pid) {
	$path = $pid % 4096;
	$hash_path = sprintf ( "/%02X/%02X/%02X", ($path >> 8) & 0xF, ($path >> 4) & 0xF, $path & 0xF );
	return $hash_path;
}

//截取字符串，支持中英文
function cutstr($string, $sublen, $start = 0, $code = 'utf-8') {
	
	if ($code == 'utf-8') 

	{
		
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		
		preg_match_all ( $pa, $string, $t_string );
		
		if (count ( $t_string [0] ) - $start > $sublen)
			return join ( '', array_slice ( $t_string [0], $start, $sublen ) ) . "...";
		
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) );
	
	} else 

	{
		
		$start = $start * 2;
		
		$sublen = $sublen * 2;
		
		$strlen = strlen ( $string );
		
		$tmpstr = '';
		
		for($i = 0; $i < $strlen; $i ++) 

		{
			
			if ($i >= $start && $i < ($start + $sublen)) 

			{
				
				if (ord ( substr ( $string, $i, 1 ) ) > 129) 

				{
					
					$tmpstr .= substr ( $string, $i, 2 );
				
				} 

				else 

				{
					
					$tmpstr .= substr ( $string, $i, 1 );
				
				}
			
			}
			
			if (ord ( substr ( $string, $i, 1 ) ) > 129)
				$i ++;
		
		}
		
		// 超出多余的字段就显示...
		
		if (strlen ( $tmpstr ) < $strlen)
			$tmpstr .= "...";
		
		return $tmpstr;
	
	}
}

//计算中英文字符串长度
function abslength($str)
{
	if(empty($str)){
		return 0;
	}
	if(function_exists('mb_strlen')){
		return mb_strlen($str,'utf-8');
	}
	else {
		preg_match_all("/./u", $str, $ar);
		return count($ar[0]);
	}
}
